package com.wx.rabbitmq.admin;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author wx
 * @Description: RabbitAdmin使用操作
 * @date 2018/11/24 002418:53
 */
@RestController
public class RabbitAdminController {

    @Autowired
    private RabbitAdmin rabbitAdmin;
    
    /**
     * @description: 创建交换机、队列并绑定
     * @author: wx
     * @date: 2018/11/24 0024
     * @param 
     * @return: java.lang.String
     */
    @PostMapping("/testAdmin")
    public String testAdmin() {
        /** Start 创建交换机、队列并绑定  使用方式1 */
        //创建direct类型交换机
        rabbitAdmin.declareExchange(new DirectExchange("test.direct", false, false));
        //创建队列
        rabbitAdmin.declareQueue(new Queue("test.direct.queue", false));
        //绑定操作
        rabbitAdmin.declareBinding(new Binding("test.direct.queue",
                Binding.DestinationType.QUEUE,
                "test.direct", "direct", new HashMap<>()));
        /** End */

        /** Start 创建交换机、队列并绑定  使用方式2 */

        //topic类型交换机
        TopicExchange topicExchange = new TopicExchange("test.topic", false, false);
        Queue topicQueue = new Queue("test.topic.queue", false);
        rabbitAdmin.declareExchange(topicExchange);
        rabbitAdmin.declareQueue(topicQueue);
        rabbitAdmin.declareBinding(
                BindingBuilder
                        //直接创建队列
                        .bind(topicQueue)
                        //直接创建交换机 建立关联关系
                        .to(topicExchange)
                        //指定路由Key
                        .with("user.#"));


        //fanout类型交换机
        FanoutExchange fanoutExchange = new FanoutExchange("test.fanout", false, false);
        Queue fanoutQueue = new Queue("test.fanout.queue", false);
        rabbitAdmin.declareExchange(fanoutExchange);
        rabbitAdmin.declareQueue(fanoutQueue);
        rabbitAdmin.declareBinding(
                BindingBuilder
                        .bind(fanoutQueue)
                        .to(fanoutExchange));

        /** End */


        //清空队列数据
        rabbitAdmin.purgeQueue("test.topic.queue", false);
        return "成功";
    }
}
